<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>使用future机制和对象锁实现SynchronizedExecutor | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第九篇博客–使用future机制和对象锁实现SynchronizedExecutor futurefuture代表一个任务的预执行结果，通过get方法获取执行结果123public interface Future&amp;lt;V&amp;gt; &amp;#123;	V get() throws Exception;&amp;#125; callablecallable代表一个要执行的任务，执行方法cal">
<meta property="og:type" content="article">
<meta property="og:title" content="使用future机制和对象锁实现SynchronizedExecutor">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/03/23/使用future机制和对象锁实现SynchronizedExecutor/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第九篇博客–使用future机制和对象锁实现SynchronizedExecutor futurefuture代表一个任务的预执行结果，通过get方法获取执行结果123public interface Future&amp;lt;V&amp;gt; &amp;#123;	V get() throws Exception;&amp;#125; callablecallable代表一个要执行的任务，执行方法cal">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-03-26T00:33:37.885Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用future机制和对象锁实现SynchronizedExecutor">
<meta name="twitter:description" content="欢迎查看Eetal的第九篇博客–使用future机制和对象锁实现SynchronizedExecutor futurefuture代表一个任务的预执行结果，通过get方法获取执行结果123public interface Future&amp;lt;V&amp;gt; &amp;#123;	V get() throws Exception;&amp;#125; callablecallable代表一个要执行的任务，执行方法cal">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-使用future机制和对象锁实现SynchronizedExecutor" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/03/23/使用future机制和对象锁实现SynchronizedExecutor/" class="article-date">
  	<time datetime="2019-03-23T07:06:42.851Z" itemprop="datePublished">2019-03-23</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      使用future机制和对象锁实现SynchronizedExecutor
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第九篇博客–使用future机制和对象锁实现SynchronizedExecutor</p>
<h2 id="future"><a href="#future" class="headerlink" title="future"></a>future</h2><p>future代表一个任务的预执行结果，通过get方法获取执行结果<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface Future&lt;V&gt; &#123;</span><br><span class="line">	V get() throws Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="callable"><a href="#callable" class="headerlink" title="callable"></a>callable</h2><p>callable代表一个要执行的任务，执行方法call，执行完成返回一个值<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface Callable&lt;V&gt; &#123;</span><br><span class="line">	V call() throws Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="executor"><a href="#executor" class="headerlink" title="executor"></a>executor</h2><p>executor为执行器，通过执行器来执行任务并得到预执行结果对象future<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface Executor&lt;V&gt; &#123;</span><br><span class="line">	Future&lt;V&gt; execute(Callable&lt;V&gt; callable);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="SynchronizedExecutor"><a href="#SynchronizedExecutor" class="headerlink" title="SynchronizedExecutor"></a>SynchronizedExecutor<v></v></h2><p>使用synchronized关键字实现的执行器<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">public class SynchronizedExecutor&lt;V&gt; implements Executor&lt;V&gt; &#123;</span><br><span class="line">	</span><br><span class="line">	static class ExecutorThread&lt;V&gt; extends Thread&#123;</span><br><span class="line">		public Object lock;</span><br><span class="line">		public V result;</span><br><span class="line">		public Callable&lt;V&gt; task;</span><br><span class="line">		public Exception e;</span><br><span class="line">		public boolean isDone = <span class="literal">false</span>;</span><br><span class="line">		public ExecutorThread(Callable&lt;V&gt; task,Object lock) &#123;</span><br><span class="line">			this.lock = lock;</span><br><span class="line">			this.task = task;</span><br><span class="line">		&#125;</span><br><span class="line">		@Override</span><br><span class="line">		public void <span class="function"><span class="title">run</span></span>() &#123;</span><br><span class="line">			try &#123;</span><br><span class="line">				result = task.call();</span><br><span class="line">			&#125; catch (Exception e) &#123;</span><br><span class="line">				this.e = e;</span><br><span class="line">			&#125;finally &#123;</span><br><span class="line">				synchronized (lock) &#123;</span><br><span class="line">					//需持有锁才能调用notify</span><br><span class="line">					this.isDone = <span class="literal">true</span>;</span><br><span class="line">					lock.notifyAll();</span><br><span class="line">					//此处的加锁只是为了获得锁</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public Future&lt;V&gt; execute(Callable&lt;V&gt; callable) &#123;</span><br><span class="line">		Object lock = new Object();</span><br><span class="line">		ExecutorThread&lt;V&gt; thread = new ExecutorThread&lt;V&gt;(callable,lock);</span><br><span class="line">		thread.start();</span><br><span class="line">		Future&lt;V&gt; future = new Future&lt;V&gt;() &#123;</span><br><span class="line"></span><br><span class="line">			@Override</span><br><span class="line">			public V get() throws Exception &#123;</span><br><span class="line">				synchronized (lock) &#123;</span><br><span class="line">					//通过锁机制，使得未完成时，get方法陷入等待队列，让出cpu给别的线程，异步完成时再唤醒</span><br><span class="line">					//需持有锁才能调用<span class="built_in">wait</span></span><br><span class="line">					<span class="keyword">while</span>(!thread.isDone) &#123;</span><br><span class="line">						lock.wait();</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">if</span>(thread.e != null) &#123;</span><br><span class="line">						throw thread.e;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="built_in">return</span> thread.result;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">		&#125;;</span><br><span class="line"></span><br><span class="line">		<span class="built_in">return</span> future;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>优点:通过多线程执行并立即返回一个Future对象,而不等待任务，使得源线程继续执行，<br>只有当源线程需要多线程执行结果，调用其get方法时，通过创建执行线程时创建的对象锁来阻塞线程直到任务执行完成<br>当执行过程中如果有抛出异常,则先捕获该异常，在调用get执行结果时再抛出</p>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/03/23/HashMap、TreeMap、HashTable、ConcurrentHashMap对比/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          HashMap、TreeMap、HashTable、ConcurrentHashMap对比(jdk1.8)
        
      </div>
    </a>
  
  
    <a href="/blog/2019/03/23/JUC相关/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">JUC相关</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="使用future机制和对象锁实现SynchronizedExecutor" data-title="使用future机制和对象锁实现SynchronizedExecutor" data-url="http://eetal.gitee.io/blog/blog/2019/03/23/使用future机制和对象锁实现SynchronizedExecutor/"  data-images="/blog/images/head.jpg" data-content="使用future机制和对象锁实现SynchronizedExecutor">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>